#!/usr/bin/env node
import fs from 'fs'
import path from 'path'
import sizeOf from 'image-size'
import chalk from 'chalk'
import Table from 'cli-table3'

interface ImageInfo {
    name: string
    size: number
    width: number
    height: number
    type: string
}

// Supported image file extensions
const IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']

async function getImageInfo(): Promise<ImageInfo[]> {
    const files = fs.readdirSync(process.cwd())
    const imageInfos: ImageInfo[] = []

    for (const file of files) {
        const filePath = path.join(process.cwd(), file)
        const stats = fs.statSync(filePath)

        // Check if the file has a valid image extension
        const ext = path.extname(file).toLowerCase()
        if (stats.isFile() && IMAGE_EXTENSIONS.includes(ext)) {
            const dimensions = sizeOf(filePath)
            if (dimensions.width && dimensions.height) {
                imageInfos.push({
                    name: file,
                    size: stats.size,
                    width: dimensions.width,
                    height: dimensions.height,
                    type: dimensions.type || 'unknown',
                })
            }
        }
    }

    return imageInfos
}

async function main() {
    try {
        const imageInfos = await getImageInfo()
        const table = new Table({
            head: [chalk.bold.blue('Name'), chalk.bold.blue('Size (bytes)'), chalk.bold.blue('Dimensions'), chalk.bold.blue('Type')],
            colWidths: [30, 15, 15, 10],
            style: { 'padding-left': 1, 'padding-right': 1 }
        })

        imageInfos.forEach((info) => {
            table.push([
                chalk.green(info.name),
                chalk.yellow(info.size.toString()),
                chalk.cyan(`${info.width}x${info.height}`),
                chalk.magenta(info.type)
            ])
        })

        console.log(chalk.bold.blue('\nImage Information:\n'))
        console.log(table.toString())
    } catch (error) {
        if (error instanceof Error) {
            console.error(chalk.red('Error:', error.message))
        } else {
            console.error(chalk.red('An unknown error occurred'))
        }
    }
}

main()